<?php

namespace App\Imports;

use Exception;

trait BaseImportTrait
{
    private $no_error = true;
    private $error_field = '';

    //验证字段是否存在(即excel 的列项是否存在)
    private function verifyField(array $row)
    {
        // dd($row);
        $pass = true;
        $field_name = '';
        foreach ($this->required_field as $field) {
            if (!array_key_exists($field, $row)) {
                $pass = false;
                $field_name = $field;
                break;
            }
        }

        if (!$pass) {
            throw new Exception("该文件缺少 [ " . $field_name . " ] 列项");
        }
    }


    //验证字段不能为空
    private function verifyNotNull(array $row, int $index)
    {
        foreach ($this->required_field as $field) {
            if ($row[$field] === '') {
                $this->no_error = false;
                $this->error_field = $field;
                break;
            }
        }
        if (!$this->no_error) {
            throw new Exception('第 ' . $index . ' 行中的 [' . $this->error_field . '] 列项缺少内容值');
        }
    }
}
